/**
 * @description  场外基金指令
 *   type:type 引入模块的类型 1-指令新增，2-簿记新增，3-详情，10-存续管理/交易录入 11-组合试算/场外基金 ,confirmEdit-簿记查询列表的点击确定可编辑数据 ，confirmView:簿记查询确定之后，展示详情 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Modal } from 'antd';
import { PrimaryGhostC, PrimaryC } from '../../../comps';
import TradeElementsC from './common/tradeElements'; // 指令/簿记下达
import { uniqueKey } from '../../../utils/commonFunc';
@Form.create()
class AddFunTradeC extends PureComponent {
  static defaultProps = {
    onRef: () => {}, //父组件调用
    onOk: () => {}, //新增成功通知父组件
    onCancel: () => {}, //取消通知父组件
    fundTypeOnchange: () => {},
    portfolioOnChange: () => {},
    secucodeOnChange: () => {},
  };
  constructor() {
    super();
    this.state = {
      querys: {}, // 发给接口的数据
      isShow: false, //二次弹窗 指令用到
      queryModal: {}, //二次弹窗 下达数据
      // trailColumns: [],//试算结果列表 试算暂时去掉了
      // trailDataSource: [],//试算结果数据
      // trailModel: false,//试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '', //
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const uid = uniqueKey(); //用于下达请求时 后端识别是否时最新请求用的 前端无用
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  // 组合变更事件 得到组合对象
  portfolioOnChange = (e) => {
    this.props.portfolioOnChange(e); //通知父组件变更组合
    if (this.props.type == '1') this.queryIsAccountConfigured(e); //指令下达才进入这个判断
  };
  //指令才需要判断是否可下达
  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  addData = () => {
    const {
      type,
      userM: { currentUser = {} },
      position = {},
      money = {},
      info,
    } = this.props;
    const { uid } = this.state;
    const data = this.AddFund.getInfo();
    if (data !== undefined) {
      const datas = _.cloneDeep(data);
      delete datas.fundInfo;
      delete datas.rollInCodeInfo;
      if (type == '10') {
        datas.portfolioId = datas.listId;
        datas.productId = null;
        delete datas.listId;
      }
      datas.isPublic = data.fundTypeSelect;
      datas.fundId = data.fundInfo.tradingCode;
      datas.securityId = data.fundInfo.tradingCode;
      datas.orderman = info ? info.userId : currentUser.userId; //下达人Id
      datas.exchangeCode = data.fundInfo.exchangeCode;
      datas.fundName = data.fundInfo.secuabbr;
      //转换的数据被删除了  这里应该用不上
      // datas.rollInCode = data.rollInCodeInfo?.tradingCode;
      // datas.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
      // datas.rollInName = data.rollInCodeInfo?.secuabbr;
      const query = {
        method: type == '1' || type == '10' ? null : '0',
        userId: currentUser.userId,
        userName: currentUser.name,
        trade5: datas,
        type: '5',
        remark: data.remark,
        uid: uid,
      };
      if (type == '1' || type == '2' || type == '11') {
        this.setState(
          {
            querys: query,
          },
          () => {
            /**
           *【委托方向】为“申购”1，需要完成“验资”：【申购金额】 < T+0可用
            【委托方向】为“赎回”2，需要完成“验券”：【赎回份额】 <= 可用数量
            【委托方向】为“认购”0，需要完成“验资”：【认购金额】 < T+0可用
            【委托方向】为“分红”6，无需额外业务校验。
           * 
           * */
            if (query.trade5.applyMethod === '1' || query.trade5.applyMethod === '0') {
              if (money.t0) {
                if (query.trade5.applyAmount < money.t0) {
                  this.setData();
                } else {
                  message.error(`${query.trade5.applyMethod === '0' ? '认购' : '赎回'}金额不能大于T+0可用资金`);
                }
              } else {
                message.error('无可用资金');
              }
            } else if (query.trade5.applyMethod === '2') {
              if (position.available) {
                if (query.trade5.applyNum <= position.available) {
                  this.setData();
                } else {
                  message.error('赎回份额不能大于可用数量');
                }
              } else {
                message.error('无可用份额');
              }
            } else {
              //其余情况不校验
              this.setData();
            }
          },
        );
      } else if (type == '10') {
        //交易录入不校验
        this.setState(
          {
            querys: query,
          },
          () => {
            this.setData();
          },
        );
      }
    }
  };
  // 点击下达或确定
  handleOnClick = () => {
    const {
      type,
      userM: { currentUser = {} },
    } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.AddFund.getInfo();
    if (data !== undefined) {
      const datas = _.cloneDeep(data);
      delete datas.fundInfo;
      delete datas.rollInCodeInfo;
      datas.trade5 = { ...datas };
      datas.trade5.isPublic = data.fundTypeSelect;
      datas.trade5.fundId = data.fundInfo.tradingCode;
      datas.trade5.exchangeCode = data.fundInfo.exchangeCode;
      datas.userName = currentUser.userId;
      datas.trade5.fundName = data.fundInfo.secuabbr;
      datas.trade5.rollInCode = data.rollInCodeInfo?.tradingCode;
      datas.trade5.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
      datas.trade5.rollInName = data.rollInCodeInfo?.secuabbr;
      datas.trade5.fee = data.fee;
      if (type == '1') {
        //指令下达有二次确认弹窗
        this.setState({ queryModal: datas }, () => {
          this.setState({ isShow: true });
        });
      } else {
        this.addData();
      }
    }
  };
  // 指令下达或新增簿记 组合试算下达 交易录入下达
  setData = () => {
    const { dispatch, type, info } = this.props;
    const { querys } = this.state;
    if (type == '1') {
      dispatch({
        //指令
        type: 'newFundTrade/SaveInstruction',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.AddFund.reset();
          this.setState({
            isShow: false,
            isCanOrder: true,
          });
          this.props.portfolioOnChange(); //通知父组件变更组合
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '2') {
      dispatch({
        //场外基金簿记
        type: 'newFundTrade/SaveInstructionw2',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.AddFund.reset();
          this.props.portfolioOnChange(); //通知父组件变更组合
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '10') {
      //交易录入
      dispatch({
        type: 'newFundTrade/tradeBookSave',
        payload: querys,
        callback: (res) => {
          this.props.onOk();
          this.AddFund.reset();
          this.props.portfolioOnChange(); //通知父组件变更组合
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '11') {
      //组合试算
      dispatch({
        type: 'portfolioTrialAddM/fundTradeSave',
        payload: querys,
        callback: (res) => {
          if (res && res.success == true) {
            this.props.onOk();
            this.AddFund.reset();
            this.props.portfolioOnChange(); //通知父组件变更组合
            message.success('组合试算新增成功');
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    }
  };

  // 取消方法
  reset = () => {
    this.AddFund.reset();
    const { type } = this.props;
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };
  //簿记查询列表里的确定按钮
  confirmOk = () => {
    const data = this.AddFund.getInfo();
    if (!data) return;

    const applyAmount = data.applyAmount;
    const applyNum = data.applyNum;

    this.props.dispatch({
      type: 'newFundTrade/confirmEdit',
      payload: {
        id: this.props.info.id,
        applyAmount,
        applyNum,
        applyInt: data.applyInt || 0,
        applyTotalAmount: data.applyTotalAmount || 0,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            message.success('保存成功！');
            this.props.onCancel('refresh');
          } else {
            message.error(res.msg || '保存失败！');
          }
        } else {
          message.error('保存失败！');
        }
      },
    });
  };

  // 下方按钮
  showBtn = () => {
    const { type, loading } = this.props;
    if (type == '1' || type == '2' || type == '10' || type == '11') {
      let url =
        type == '1'
          ? 'newFundTrade/SaveInstruction'
          : type == '2'
          ? 'newFundTrade/SaveInstructionw2'
          : type == '11'
          ? 'portfolioTrialAddM/fundTradeSave'
          : 'newFundTrade/tradeBookSave';
      return (
        <div style={{ float: 'right', marginTop: '20px' }}>
          {/* {type == "2" && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "10px" }}
          />} */}
          <PrimaryC loading={loading.effects[url] === true} onClick={() => this.handleOnClick()} title={type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={() => this.reset()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    } else {
      return null;
    }
  };

  // 二次确认点击确定
  handleOk = () => {
    this.addData();
  };
  // 二次确认点击取消
  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  // 二次确认model框 指令需要的
  showModal = () => {
    const { queryModal, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认下达',
      width: 700,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <Modal {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={loading.effects['newFundTrade/SaveInstruction'] === true}>
          <AddFund type={'3'} info={queryModal} />
        </Modal>
      </div>
    );
  };
  //投资类型改变响应
  investmentChange = () => {};
  //试算按钮点击 不做
  // trialOnClick = () => {
  //   const {  productCode, portfolioCode } = this.state;
  //   const { type, dispatch,userM:{currentUser={}} } = this.props
  //   const data = this.AddFund.getInfo();
  //   if (data !== undefined) {
  //     const datas = _.cloneDeep(data);
  //     delete datas.fundInfo;
  //     delete datas.rollInCodeInfo;
  //     datas.userName = currentUser.userId;
  //     datas.isPublic = data.fundTypeSelect;
  //     datas.fundId = data.fundInfo.tradingCode;
  //     datas.securityId = data.fundInfo.tradingCode;
  //     datas.orderman = currentUser.userId;
  //     datas.exchangeCode = data.fundInfo.exchangeCode;
  //     datas.fundName = data.fundInfo.secuabbr;
  //     datas.rollInCode = data.rollInCodeInfo?.tradingCode;
  //     datas.rollnExchangeCode = data.rollInCodeInfo?.exchangeCode;
  //     datas.rollInName = data.rollInCodeInfo?.secuabbr;
  //     const query = {
  //       method: (type == '1' || type == '10') ? null : '0',
  //       userId: currentUser.userId,
  //       userName: currentUser.name,
  //       productCode: productCode, //产品code
  //       portfolioCode: portfolioCode, //组合code
  //       tenant: currentUser.tenant,//租户code
  //       trade5: datas,
  //       type: '5',
  //       remark: data.remark,
  //       businessType: '5',
  //     };
  //     this.setState({ trailModel: true }, () => {
  //       dispatch({
  //         type: "trailM/trialData",
  //         payload: query,
  //         callback: res => {
  //           if (res) {
  //             this.setState({
  //               trailColumns: res.columns,
  //               trailDataSource: res.dataSource
  //             });
  //           } else {
  //             this.setState({
  //               trailColumns: [],
  //               trailDataSource: []
  //             });
  //           }

  //         }
  //       });
  //     });

  //   }
  // }
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };

  //试算结果列表优化
  // trailColumnsChange = (data) => {
  //   if (data) {
  //     data?.map(item => {
  //       if (item.key == 'ruleDesc') {
  //         item.ellipsis = true
  //       } else {
  //         item.width = '125px'
  //       }

  //     })
  //   }
  //   return data
  // }
  //试算结果
  // showTrail = () => {
  //   const { trailModel, trailColumns, trailDataSource } = this.state
  //   const newTrailColumns = this.trailColumnsChange(trailColumns)
  //   return (
  //     <Modal
  //       visible={trailModel}
  //       title='试算结果'
  //       width={1200}
  //       onOk={() => { this.setState({ trailModel: false }) }}
  //       onCancel={() => { this.setState({ trailModel: false }) }}
  //     >
  //       <TableC
  //         columns={newTrailColumns}
  //         dataSource={trailDataSource}
  //         loading={this.props.loading.effects['trailM/trialData'] === true}
  //         scroll={{ y: '231px' }}
  //         rowKey="id"
  //         hidePage={true}
  //       />
  //     </Modal>
  //   )
  // }
  render() {
    const { type, position, fundTypeOnchange, secucodeOnChange, listId, info } = this.props;
    const { isShow } = this.state;
    return (
      <div style={{ marginTop: '10px', height: '50px' }}>
        <TradeElementsC
          fundTypeOnchange={fundTypeOnchange}
          onRef={(ref) => (this.AddFund = ref)}
          portfolioOnChange={this.portfolioOnChange}
          secucodeOnChange={secucodeOnChange}
          type={type}
          portfolioCode={this.portfolioCode}
          productCode={this.productCode}
          position={position}
          listId={listId}
          info={info}
        />
        <div>{this.showBtn()}</div>
        <div>{isShow ? <div>{this.showModal()}</div> : null}</div>
      </div>
    );
  }
}

export default connect(({ userM, newFundTrade, interBankBasicInfoM, portfolioTrialAddM, loading, trailM, isAccountConfiguredM }) => ({
  userM,
  newFundTrade,
  interBankBasicInfoM,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(AddFunTradeC);
